#! /bin/bash

#ENV
basepath=$(cd `dirname $0`; pwd)
echo "base path:${basepath}"
workpath=${1:-${basepath}}
echo "workspace: ${workpath}"

artifactsDir="${workpath}/artifacts"
artifactsWarDir="${artifactsDir}/war"
artifactsWarFileName=$(ls ${artifactsWarDir} -ltr |tail -1|awk '{print $NF}')
warFilePath="${artifactsWarDir}/${artifactsWarFileName}"

workDir="${workpath}/work"
volumeDir="${workDir}/webapi"

if [ -f "${warFilePath}" ]
then
	#clean volume
	echo "clean volume ${volumeDir}"
	rm -rf ${volumeDir}
	#unzip
	echo "unzip war file ${warFilePath}"
	unzip  -q -d ${volumeDir} ${warFilePath}
fi

#stop running containers
echo "stop running containers..."
docker stop `docker ps -a | grep cus_api | awk '{print $1}'`
#remove containers
echo "remove containers"
docker rm `docker ps -a | grep cus_api | awk '{print $1}'`

#start container
count=${2:-2}
index=0
while(( $index < $count ))
do
	port=`expr 9090 + $index`
	name="cus_api${index}"
	echo "start container ${name} on port: ${port}"
	docker run -idt --link redis:redis --name ${name} -e TZ="Asia/Shanghai" -v /etc/localtime:/etc/localtime -v ${volumeDir}:/usr/local/tomcat/webapps/ROOT -p ${port}:8080 tomcat:8.5
	let "index++"
done

